import { Body, Controller, Get, Param, Post } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { LeaveMessage, LeaveMessageQuery } from '../entity/leaveMessage.entity';
import { requestBody } from '../interface/layout';
import { formatDate } from '../commen/tool';

@Controller('/leavemessage')
export class LeaveMessageController {
  @InjectEntityModel(LeaveMessage)
  repoLeaveMessage: Repository<LeaveMessage>;
  @Post('/insert')
  async insert(@Body() leaveMessage: LeaveMessage) {
    leaveMessage.msgID = String(Date.now());
    // if (typeof transport.transportId !== 'string')
    const time = formatDate(new Date());
    leaveMessage.createDate = time;
    leaveMessage.isRead = false;
    const Msg = await this.repoLeaveMessage.save(leaveMessage);
    return <requestBody>{
      code: 0,
      msg: '留言成功',
      data: Msg,
    };
  }
  @Post('/query')
  async query(@Body() qc: LeaveMessageQuery) {
    const { name, pageIndex, pageSize, DateBegin, DateEnd } = qc;
    const pageStart = (pageIndex - 1) * pageSize;
    const builder = this.repoLeaveMessage.createQueryBuilder('t');
    if (name) {
      builder.andWhere('t.name like :s', { s: '%' + name + '%' });
    }
    if (DateBegin) {
      builder.andWhere('t.createDate >= :DateBegin', { DateBegin });
    }
    if (DateEnd) {
      builder.andWhere('t.createDate <= :DateEnd', { DateEnd });
    }
    builder.orderBy('t.createDate', 'DESC').offset(pageStart).limit(pageSize);
    const result = await builder.printSql().getManyAndCount();
    return <requestBody>{
      code: 0,
      msg: '',
      data: { results: result[0], total: result[1] },
    };
  }
  @Get('/delete/:msgID')
  async delete(@Param('msgID') msgID: string) {
    const msg = await this.repoLeaveMessage.findOne({
      where: {
        msgID: msgID,
      },
    });
    if (!msg) {
      return <requestBody>{
        code: -1,
        msg: '留言不存在',
        data: msgID,
      };
    }
    const result = await this.repoLeaveMessage.remove(msg);
    return <requestBody>{
      code: 0,
      msg: '删除成功',
      data: result,
    };
  }
  @Get('/read/:msgID')
  async reade(@Param('msgID') msgID: string) {
    const msg = await this.repoLeaveMessage.findOne({
      where: {
        msgID: msgID,
      },
    });
    if (!msg) {
      return <requestBody>{
        code: -1,
        msg: '留言不存在',
        data: msgID,
      };
    }
    msg.isRead = true;
    const result = await this.repoLeaveMessage.save(msg);
    return <requestBody>{
      code: 0,
      msg: '修改成功',
      data: result,
    };
  }
}
